import settings from '@/settings'
/** key前缀 */
const keyPrefix = settings.app.storagePrefix
/**
 * 是否过期
 */
const isFresh = valObj => {
  const now = new Date().getTime()
  return valObj.addTime + valObj.expires >= now
}

/* 给key值添加前缀 */
const addPrefix = key => {
  return `${keyPrefix}${key}`
}
const storage = {
  local: {
    set(key, value, expires) {
      const skey = addPrefix(key)
      if (expires) {
        localStorage.setItem(
          skey,
          JSON.stringify({
            value,
            addTime: new Date().getTime(),
            expires
          })
        )
      } else {
        const val = JSON.stringify(value)
        localStorage.setItem(skey, val)
      }
      if (value === undefined || value === null) {
        localStorage.removeItem(skey)
      }
    },
    get(key) {
      const skey = addPrefix(key)
      const item = JSON.parse(localStorage.getItem(skey))

      // 如果有addTime的值，说明设置了失效时间
      if (item && item.addTime) {
        if (isFresh(item)) {
          return item.value
        }
        /* 缓存过期，清除缓存，返回null */
        localStorage.removeItem(skey)
        return null
      }
      return item
    },
    has(key) {
      const skey = addPrefix(key)
      return !!localStorage.getItem(skey)
    },
    remove: key => {
      const skey = addPrefix(key)
      localStorage.removeItem(skey)
    },
    clear: () => {
      localStorage.clear()
    },
    clearSelf: () => {
      const arr = Array.from({ length: localStorage.length }, (_, i) => localStorage.key(i)).filter(str =>
        str?.startsWith(keyPrefix)
      )
      arr.forEach(str => localStorage.removeItem(str))
    }
  },
  session: {
    has: key => {
      return !!sessionStorage.getItem(`${settings.app.storagePrefix}${key}`)
    },
    get: key => {
      const item = sessionStorage.getItem(`${settings.app.storagePrefix}${key}`)
      return item ? JSON.parse(sessionStorage.getItem(`${settings.app.storagePrefix}${key}`)) : item
    },
    set: (key, value) => {
      sessionStorage.setItem(`${settings.app.storagePrefix}${key}`, JSON.stringify(value))
    },
    remove: key => {
      sessionStorage.removeItem(`${settings.app.storagePrefix}${key}`)
    },
    clear: () => {
      sessionStorage.clear()
    }
  }
}

export default storage
